package com.bw.kf.all2211a.login

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.kf.all2211a.R
import com.bw.kf.all2211a.databinding.ActivityMainBinding
import com.bw.kf.all2211a.fg.HomeActivity
import com.bw.kf.all2211a.room.APPDBUser
import com.bw.kf.mvvm.base.BaseActivity
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Route(path = "/app/login/MainActivity")
class MainActivity : BaseActivity<ActivityMainBinding,LoginRepo>() {
    override fun iniView() {
        binding.url="http://i0.hdslb.com/bfs/article/e7d4a05a98483de73c2fb6359d01720e487b2d92.jpg"
        binding.getCode.isEnabled=false
        binding.dl.isEnabled=false
        binding.username.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if(s != null) {
                    if(RegexUtils.isMobileSimple(s)){
                        binding.getCode.isEnabled=true
                    }else{
                        binding.getCode.isEnabled=false
                    }
                }
            }

        })
        binding.messdl.setOnClickListener {
             val editText=EditText(this)
              AlertDialog.Builder(this)
                 .setTitle("请输入密码")
                 .setView(editText)
                 .setPositiveButton("确定") { _,_ ->
                         val phone = binding.username.text.toString()
                         val code = editText.text.toString()
                         viewModel.Mlogin(phone, code)
                 }
                  .setNeutralButton("取消") { dieo,_ ->
                        ToastUtils.showLong("取消登录")
                      dieo.dismiss()
                  }
                  .show()
        }
        binding.getCode.setOnClickListener{
              if(!RegexUtils.isMobileSimple(binding.username.text.toString())){
                      ToastUtils.showLong("手机号不正确！")
                  return@setOnClickListener;
              }
              val phone = binding.username.text.toString()
              viewModel.sendCode(phone)
            binding.getCode.isEnabled=false
            lifecycleScope.launch {
                for (i in 15 downTo 1){
                    binding.getCode.text="重新获取($i)"
                    delay(1000)
                }
                binding.getCode.isEnabled=true
                binding.getCode.text="获取验证码"
            }
          }
        binding.dl.setOnClickListener{
            if(!binding.cb.isChecked){
                AlertDialog.Builder(this)
                    .setTitle("请先阅读并同意《用户协议》和《隐私政策》")
                    .setMessage("请先阅读并同意《用户协议》和《隐私政策》")
                    .setPositiveButton("确定") { _,_ ->
                        binding.cb.isChecked=true
                    }
                    .setNegativeButton("取消") { dialog, _ ->
                        dialog.dismiss()
                    }
                    .show()
                return@setOnClickListener;
            }
            val phone = binding.username.text.toString()
            val code = binding.code.text.toString()
            viewModel.login(phone, code)
        }
        //富文本
        val span=SpannableStringBuilder(binding.cb.text.toString())
        span.setSpan(ForegroundColorSpan(Color.RED),6,12,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        val chickenspan=object:ClickableSpan(){
            @SuppressLint("SuspiciousIndentation")
            override fun onClick(widget: android.view.View) {
            ARouter.getInstance().build("/app/login/WebActivity")
                .withString("url","https://www.bilibili.com")
                .navigation()
            }
        }
        span.setSpan(chickenspan,13,19,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        binding.cb.movementMethod=LinkMovementMethod.getInstance()
        binding.cb.text=span


    }
    override fun iniData() {
     viewModel.success.observe(this){
         if(it.code==200){
             binding.code.setText(it.data.content.substring(8,14))
             binding.dl.isEnabled=true
         }
      ToastUtils.showLong(it.message)
     }
   viewModel.successL.observe(this){
       if(it.code==200){
          SPUtils.getInstance().put("token", it.data.token)
           ToastUtils.showLong("登录成功")
           SPUtils.getInstance().put("phone",it.data.phone)
           APPDBUser.getDb().getUserDao().insertUser(it.data)
           val queryUser = APPDBUser.getDb().getUserDao().queryUser(SPUtils.getInstance().getString("phone"))
           queryUser.forEach{
               Log.d("initView","昵称为${it.nikeName}，令牌${it.token}，手机号${it.phone}")
           }
           ARouter.getInstance().build("/app/fg/HomeActivity").navigation()
       }
       ToastUtils.showLong(it.message)
   }
        viewModel.successM.observe(this){
            if(it.code==200){
                ToastUtils.showLong("登录成功")
                SPUtils.getInstance().put("token",it.data.token)

                ARouter.getInstance().build("/app/fg/HomeActivity").navigation()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
    }
    override fun getViewModel(): Class<LoginRepo> {
        return LoginRepo::class.java
    }
    override fun Layoutid()= R.layout.activity_main
}